class UseInorderAndPostorderCreateTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return buildTreeChild(inorder,postorder,0,postIndex);
    }
    public TreeNode buildTreeChild(int[] inorder,int[] postorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findVal(inorder,inBegin,inEnd,postorder[postIndex]);
        postIndex--;
        root.right = buildTreeChild(inorder,postorder,rootIndex+1,inEnd);
        root.left = buildTreeChild(inorder,postorder,inBegin,rootIndex-1);
        return root;
    }
    private int findVal(int[] inorder,int inBegin,int inEnd,int val) {
        for(int i = inBegin; i <= inEnd;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }

    public String tree2str(TreeNode root) {
        StringBuilder sbd = new StringBuilder();
        tree2strChild(root,sbd);
        return sbd.toString();
    }
    public void tree2strChild(TreeNode root,StringBuilder sbd) {
        if(root == null) return;
        sbd.append(root.val);
        if(root.left != null) {
            sbd.append("(");
            tree2strChild(root.left,sbd);
            sbd.append(")");
        }else {
            if(root.right == null) {
                return;
            }else {
                sbd.append("()");
            }
        }
        if(root.right != null) {
            sbd.append("(");
            tree2strChild(root.right,sbd);
            sbd.append(")");
        }else {
            return;
        }
    }

}